library("quantmod");
# rm(list=ls())
# Load stock symbols from List
Debug = F;
stock_clusting = function (ListFile) {
	sample_count = 10;
	stock_sample = stock_sample(ListFile, sample_count);
	
	cluster_result = kmeans(stock_sample, 3, nstart=5);

}

sample_stock = function(ListFile, SampleCount) {
    stock_list = read.csv(ListFile, colClasses="character", head=F);
    record = data.frame(matrix(integer(0), ncol=SampleCount)); 
    record_colName = paste(rep("sample", SampleCount), seq(1, SampleCount), sep="");
    colnames(record) = record_colName;
    index = 1; 
    for (stock_name in stock_list$V1) {
        sample = sample_price(stock_name, SampleCount);
        #colnames(sample) = record_colName;
	record[index,] =  sample;
     	index = index + 1;
    }
    #write.csv(record, "stock_sample.txt", col.names=F);
    return (record);
}

sample_ema = function(StockName, SampleCount) {
    try({
    	stock = getSymbols(StockName, auto.assign=F);
    	close = stock[,4];
	ema = EMA(close, 20);
    	total_length = length(ema);
	# Truck latest 200 record.
	ema = ema[total_length-200 : total_length];
	total_length = length(ema);
	# Calculate spread.
	spread = (ema[2:total_length] - ema[1:total_length-1]) / ema[1:total_length-1];
	spread_length = length(spread);
	# Sample the spread result.
	sample_step = round(spread_length / SampleCount);
	sample_index = seq(1, spread_length, by=sample_step);
	sample_spread = spread[sample_index];
	return (sample_spread);
    }); # End of try function.
}

sample_price = function(StockName, SampleCount) {
    try({
	stock = getSymbols(StockName, auto.assign=F);
	close = stock[,4];
	sma20 = SMA(close, 20);
	total_length = length(sma20);
	sma = sma20[(total_length-200) : total_length];
	total_length = length(sma);
	# Sample data
	sample_step = round(total_length / SampleCount);
        sample_index = seq(1, total_length, by=sample_step);
        sample_sma = sma[sample_index];
	# Calculate spread
	total_length = length(sample_sma);
	spread = ( as.numeric(sample_sma[2:total_length]) - as.numeric(sample_sma[1:total_length-1]) )*1000 / as.numeric(sample_sma[1:total_length-1]);
	return (spread);
    }); # End of try function.
}

sample_distance = function(data, center) {
	data_count = length(data[,1]);
	center_count = length(center[,1]);

	result = data.frame(integer(0), nrow=data_count);
	for(center_index in seq(1, center_count)) {
		
		distance = c();
		for(data_index in seq(1, data_count)) {
			a = center[center_index,];
			b = data[data_index,];
			
			distance = c(distance , sqrt(sum( (a-b)*(a-b) )) );
		}
		result[, center_index] = distance;
	}

	return (result);

}
